#!/usr/bin/env python3
# coding: utf-8
"""
2025-04-20 卡住查询
"""

from PySide6.QtCore import Slot, QSize
from PySide6.QtGui import QAction, QKeySequence,QIntValidator, QTextCursor   
from PySide6.QtWidgets import QMainWindow, QApplication, QVBoxLayout, QHBoxLayout, QPushButton, QWidget, QMessageBox, QLineEdit, QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView, QLabel,QCheckBox,QTextEdit,QComboBox
from PySide6.QtCore import Qt, QModelIndex,QMetaObject,Q_ARG
from PySide6.QtGui import QGuiApplication, QCloseEvent,QShowEvent
## from PySide6.QtCore.Qt import 


##from PySide6.QtCore import WindowState

## from top.wardyan.core.utils import winformutils
from top.wardyan.core.action.baseaction import WMainWindow,WQdialog
from top.wardyan.core.vo.vos import *
from top.wardyan.core.widges.tables import WTableView

##from warningmain import *
from top.wardyan.core.wdb.core.DBPool import POOL

from top.wardyan.core.vo.vos import *
from top.wardyan.core.wdb.core.db import *
from config import Config

## from top.wardyan.core.wdb.ui.dbconfigmain import DBConfigMainWindow

## 超过这个时间就自动强制kill掉 单位毫秒, 默认1小时
MAXCOST = Config.getconfig_int("autokill","maxcost")

SQL_LISTALL = """
SELECT  
	
	MAX(CASE WHEN er.start_time < DATEADD(DAY, -1, GETDATE()) THEN 999999999 ELSE DATEDIFF(MILLISECOND, er.start_time, GETDATE()) END) AS 耗时毫秒
		, COUNT(sp.ecid) AS 线程数
		, MAX(er.percent_complete) AS 完成比例
		, er.session_id AS 线程ID
		, MAX(er.status)  AS 状态
		, MAX(er.wait_type) AS 等待类型
		-- , OBJECT_NAME(qt.objectid) AS xObject			-- 对象
		, MAX(b.name) AS 名称
		, MAX(SUBSTRING(qt.text, er.statement_start_offset / 2, ( CASE	WHEN er.statement_end_offset = -1 THEN LEN(CONVERT(NVARCHAR(MAX), qt.text))* 2 ELSE er.statement_end_offset END  - er.statement_start_offset ) / 2)) AS 正在执行语句
		, MAX(qt.text) AS  来源脚本
		, MAX(er.start_time) AS 开始时间
		, MAX(er.blocking_session_id )AS 被这个线程堵塞
		, MAX(er.wait_time) AS 等待时间
		, MAX(er.wait_resource) AS 等待类型
		, MAX(er.reads) AS 物理读行
		, MAX(er.writes) AS 写行
		,MAX(er.logical_reads) AS 逻辑度行
		, MAX(er.row_count) AS 行数
		, MAX(er.cpu_time) AS CPU耗时毫秒
--		 , dp.query_plan AS xQueryPlan		-- 执行计划 可能没有
		-- more
		, MAX(DB_NAME(sp.dbid)) AS 数据库
		, MAX(sp.loginame) AS 用户
		, MAX(er.command) AS 命令
		, MAX(sp.program_name) AS 程序
		, MAX(sp.hostname) AS 主机
FROM    sys.dm_exec_requests AS  er (NOLOCK)
INNER JOIN sys.sysprocesses AS  sp (NOLOCK) ON er.session_id = sp.spid
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle) AS qt
LEFT JOIN sys.objects AS b (NOLOCK) ON b.object_id = qt.objectid
WHERE   er.session_id > 50 -- Ignore system spids.
AND er.session_id <> @@SPID
GROUP BY er.session_id
ORDER BY MAX(CASE WHEN er.start_time < DATEADD(DAY, -1, GETDATE()) THEN 999999999 ELSE DATEDIFF(MILLISECOND, er.start_time, GETDATE()) END) desc
"""



        

class DBConfigWindow (WQdialog) :
    
    def __init__(self) -> None:
        ##global cn
        super().__init__("DBConfigWindow")
        self.main()
        
        if self.lineeditHost:
            self.lineeditHost.setFocus()
            self.lineeditHost.setCursorPosition(0)  # 可选：将光标放在文本开头
    def main(self) :
        HEIGHT = 40
        #self.setFixedWidth(600)
        layout : QVBoxLayout = QVBoxLayout()
        layout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.setLayout(layout)
        
        
        ## 数据库类型 地址 端口 用户名 密码 数据库名
        wgtDBType : QWidget = QWidget()
        layout.addWidget(wgtDBType)
        wgtDBTypeLayout : QHBoxLayout = QHBoxLayout()
        wgtDBTypeLayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        wgtDBType.setLayout(wgtDBTypeLayout)
        lblDBType : QLabel = QLabel("数据库类型")
        lblDBType.setFixedWidth(100)
        lblDBType.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
        wgtDBTypeLayout.addWidget(lblDBType)
        self.cmbDBType : QComboBox = QComboBox()
        self.cmbDBType.addItems(["SQL Server","MySQL"])
        self.cmbDBType.setFixedWidth(300)
        wgtDBTypeLayout.addWidget(self.cmbDBType)
        

        
        wgtHost : QWidget = QWidget()
        layout.addWidget(wgtHost)
        wgtHostLayout : QHBoxLayout = QHBoxLayout()
        wgtHostLayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        wgtHost.setLayout(wgtHostLayout)
        lblHost : QLabel = QLabel("地址")
        lblHost.setFixedWidth(100)
        lblHost.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
        wgtHostLayout.addWidget(lblHost)
        # cmbDBType : QComboBox = QComboBox()
        # cmbDBType.addItems(["SQL Server","MySQL"])
        # cmbDBType.setFixedWidth(300)
        # wgtHostLayout.addWidget(cmbDBType)
        self.lineeditHost = QLineEdit()
        self.lineeditHost.setFixedWidth(300)
        self.lineeditHost.setText("127.0.0.1")
        
        wgtHostLayout.addWidget(self.lineeditHost)
        

        wgtPort : QWidget = QWidget()
        layout.addWidget(wgtPort)
        wgtPortLayout : QHBoxLayout = QHBoxLayout()
        wgtPortLayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        wgtPort.setLayout(wgtPortLayout)
        lblPort : QLabel = QLabel("端口")
        lblPort.setFixedWidth(100)
        lblPort.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
        wgtPortLayout.addWidget(lblPort)
        # cmbDBType : QComboBox = QComboBox()
        # cmbDBType.addItems(["SQL Server","MySQL"])
        # cmbDBType.setFixedWidth(300)
        # wgtPortLayout.addWidget(cmbDBType)
        self.lineeditPort = QLineEdit()
        self.lineeditPort.setFixedWidth(300)
        self.lineeditPort.setText("1433")
        # 只能输入数字而且只能输入1~65535  
        self.lineeditPort.setValidator(QIntValidator(1, 65535, self.lineeditPort))
        wgtPortLayout.addWidget(self.lineeditPort)
        
        wgtUsername : QWidget = QWidget()
        layout.addWidget(wgtUsername)
        wgtUsernameLayout : QHBoxLayout = QHBoxLayout()
        wgtUsernameLayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        wgtUsername.setLayout(wgtUsernameLayout)
        lblUsername : QLabel = QLabel("用户名")
        lblUsername.setFixedWidth(100)
        lblUsername.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
        wgtUsernameLayout.addWidget(lblUsername)
        self.lineeditUsername = QLineEdit()
        self.lineeditUsername.setFixedWidth(300)
        self.lineeditUsername.setText("sa")
        wgtUsernameLayout.addWidget(self.lineeditUsername)


        wgtPassword : QWidget = QWidget()
        layout.addWidget(wgtPassword)
        wgtPasswordLayout : QHBoxLayout = QHBoxLayout()
        wgtPasswordLayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        wgtPassword.setLayout(wgtPasswordLayout)
        lblPassword : QLabel = QLabel("密码")
        lblPassword.setFixedWidth(100)
        lblPassword.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
        wgtPasswordLayout.addWidget(lblPassword)
        self.lineeditPassword = QLineEdit()
        self.lineeditPassword.setFixedWidth(300)
        self.lineeditPassword.setText("")
        wgtPasswordLayout.addWidget(self.lineeditPassword)


        
        wgtDBName : QWidget = QWidget()
        layout.addWidget(wgtDBName)
        wgtDBNameLayout : QHBoxLayout = QHBoxLayout()
        wgtDBNameLayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        wgtDBName.setLayout(wgtDBNameLayout)
        lblDBName : QLabel = QLabel("数据库")
        lblDBName.setFixedWidth(100)
        lblDBName.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
        wgtDBNameLayout.addWidget(lblDBName)
        self.lineeditDBName = QLineEdit()
        self.lineeditDBName.setFixedWidth(300)
        self.lineeditDBName.setText("ERPDB4")
        wgtDBNameLayout.addWidget(self.lineeditDBName)


        # 重置按钮和保存按钮
        #wgtDBNameLayout.addStretch()
        wgtBtn : QWidget = QWidget()
        layout.addWidget(wgtBtn)
        wgtBtnLayout : QHBoxLayout = QHBoxLayout()
        wgtBtnLayout.setAlignment(Qt.AlignmentFlag.AlignRight)
        wgtBtn.setLayout(wgtBtnLayout)

        self.btnReset = QPushButton("重置")
        self.btnReset.setFixedWidth(100)
        self.btnReset.setFixedHeight(40)
        self.btnReset.clicked.connect(self.slot_resettablecol)
        wgtBtnLayout.addWidget(self.btnReset)
        self.btnSave = QPushButton("保存")
        self.btnSave.setFixedWidth(100)
        self.btnSave.setFixedHeight(40)
        self.btnSave.clicked.connect(self.slot_saveconfigs)
        self.btnSave.setDefault(True)
        wgtBtnLayout.addWidget(self.btnSave)


        
        # 默认光标所在
        self.lineeditHost.setFocus()
        

    # 重置
    def slot_resettablecol(self) :
        pass
        # self.lineeditHost.setText(cfgs.host)
        # self.lineeditPort.setText(str(cfgs.port))
        # self.lineeditUser.setText(cfgs.user)
        # self.lineeditPassword.setText(cfgs.password)
        # self.lineeditDatabase.setText(cfgs.database)
        # self.lineeditCharset.setText(cfgs.charset)

    # 保存
    def slot_saveconfigs(self) :
        dbtype = self.cmbDBType.currentText()
        host = self.lineeditHost.text()
        port = self.lineeditPort.text()
        username = self.lineeditUsername.text()
        password = self.lineeditPassword.text()
        database = self.lineeditDBName.text()
        ## 检查都不能为空, 为空就报错
        if dbtype == "" or host == "" or port == "" or username == "" or password == "" or database == "" :
            QMessageBox.warning(self, "错误", "数据库配置不能为空!", QMessageBox.StandardButton.Ok)
            return
        # 打开文件: dbconfig.txt 并写入
        type = "pymssql"
        if dbtype == "SQL Server" :
            type = "pymssql"
        elif dbtype == "MySQL" :
            type = "pymysql"
        # 密码加密 TODO 暂时还默认为明文
        # password = encrypt(password)

        try :
            with open("config\\dbconfig.ini", "w") as f :
                f.write(f"[db]\n")
                f.write(f"dbtype = {type}\n")
                f.write(f"host = {host}\n")
                f.write(f"port = {port}\n")
                f.write(f"user = {username}\n")
                f.write(f"password = {password}\n")
                f.write(f"database = {database}\n")
                QMessageBox.information(self, "报告", f"保存数据库配置文件成功", QMessageBox.StandardButton.Ok)
                QApplication.quit()
        except BaseException as e :
            QMessageBox.warning(self, "错误", f"保存数据库配置文件失败! {e}", QMessageBox.StandardButton.Ok)

            



    # def showEvent(self, event: QShowEvent) -> None:
    #     super().showEvent(event)
    #     if self.lineeditHost:
    #         self.lineeditHost.setFocus()
    #         self.lineeditHost.setCursorPosition(0)  # 可选：将光标放在文本开头
# if __name__ == "__main__" :     ## or 1 == 1
#     app = QApplication([])
#     w = WWarningEditor()
#     ## w = WScriptWindow()
#     w.show()
#     app.exec()

# if __name__ == "__main__" :     ## or 1 == 1
#     app = QApplication([])
#     w = DBConfigMainWindow()
#     ## w = WScriptWindow()
#     w.show()
#     app.exec()